import { AxiosRequestConfig } from './types'
import { transformRequestData, transformResponseData } from './helper/data'
import { transformRequestHeaders, parseHeaders } from './helper/headers'

const defaults: AxiosRequestConfig = {
  method: 'get',

  timeout: 0,

  headers: {
    common: {
      Accept: 'application/json, text/plain, */*'
    }
  },

  transformRequest: [
    (data: any, headers: any) => {
      // !必须先处理 headers 后处理 data, 因为transformRequestData会将 data 数据 stringify
      transformRequestHeaders(headers, data)
      return transformRequestData(data)
    }
  ],
  transformResponse: [
    (data: any, headers: any) => {
      parseHeaders(headers)
      return transformResponseData(data)
    }
  ],

  validateStatus: (status: number) => {
    return status >= 200 && status < 300
  },

  xsrfCookieName: 'XSRF-TOKEN',

  xsrfHeaderName: 'X-XSRF-TOKEN'
}

const methodsNoData = ['delete', 'get', 'head', 'options']

methodsNoData.forEach(method => {
  defaults.headers[method] = {}
})

const methodsWithData = ['post', 'put', 'patch']

methodsWithData.forEach(method => {
  defaults.headers[method] = {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})

export default defaults
